//  Created by 莫瑞权 on 2022/5/16.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TFGalleryView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, TF1to16VideoAreaCellDelegate,UICollectionViewDelegateFlowLayout {

    @objc public weak var delegate : TFGalleryViewDelegate?

    //视频view数组
    @objc public let videoSessionsArray = NSMutableArray()
    @objc public var vc:TF1to16VideoAreaCell?
    //全屏
    @objc public var isFull:Bool = false
    //显示奖杯
    @objc public var showCup:Bool = false
    @objc let layout = UICollectionViewFlowLayout()
    @objc public var collectionView:TFCollectionView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        self.layout.minimumLineSpacing = 5
        self.layout.minimumInteritemSpacing = 5
        self.collectionView = TFCollectionView.init(frame:CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: self.layout)
        
        self.collectionView!.backgroundColor = UIColor.red
        self.addSubview(self.collectionView!)
        self.collectionView!.clipsToBounds = false
        self.collectionView!.dataSource = self
        self.collectionView!.delegate = self
        self.collectionView!.alwaysBounceVertical = true
        
        if #available(iOS 11.0, *) {

            self.collectionView!.contentInsetAdjustmentBehavior = .never

        }
       //注册Cell，必须要有
        self.collectionView!.register(TF1to16VideoAreaCell.self, forCellWithReuseIdentifier: "TF1to16VideoAreaCell")
        self.collectionView!.register(TFVideoGralleryCell.self, forCellWithReuseIdentifier: "TFVideoGralleryCell")
        self.collectionView!.backgroundColor = UIColor.clear
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        if self.collectionView != nil {
            self.collectionView!.frame = self.bounds
        }
        
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = self.getCount()
        return count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if (indexPath.row < self.videoSessionsArray.count) {
            let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: "TF1to16VideoAreaCell", for: indexPath) as! TF1to16VideoAreaCell
            
            cell.ViewWidth = cell.frame.size.width
            cell.ViewHight = cell.frame.size.height
            cell.showCup = self.showCup
           
            let model = self.videoSessionsArray[indexPath.row] as! TalkfunRtcModel
            cell.model =  model
            cell.delegate = self
           
            return cell;
        } else {

            let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: "TFVideoGralleryCell", for: indexPath)
          
            return cell;

        }
    }
    
    func collectionView(_ collectionView: UICollectionView,
                            layout collectionViewLayout: UICollectionViewLayout,
                            sizeForItemAt indexPath: IndexPath) -> CGSize
        {
            return self.getSize()
        }
    @objc func exist(_ model:TalkfunRtcModel)->Bool

    {
            //是否已经存在
        var Exist:Bool = false
        for i in 0..<self.videoSessionsArray.count {
           let obj = self.videoSessionsArray[i] as! TalkfunRtcModel
        
        if (obj.xid == model.xid) {
            Exist = true

        }
         
         }
         return Exist
    }
    @objc func removeFromVideo(_ dict:TalkfunRtcModel)
    {
        if(self.isFull){
              if (self.vc != nil) {
                  self.dealSingleTap(self.vc!)
              }
          }
        
        let copy = NSMutableArray.init(array: self.videoSessionsArray)
        for i in 0..<copy.count {
            let model = copy[i] as! TalkfunRtcModel
       
            if (model.xid == dict.xid) {
                self.videoSessionsArray.remove(model)
                break;
                
            }
        }
        self.reloadData()
       
    }
    
    func reloadData()
    {
        if self.collectionView != nil {
            self.collectionView?.reloadData()
        }
    }
    // MARK: 直播结束
   @objc func liveStop()
    {
        self.videoSessionsArray.removeAllObjects()
        self.reloadData()
    }
    //关闭所有人的涂鸦
   @objc func allGraffitiCloses()
    {
        for i in 0..<self.videoSessionsArray.count {
           let model = self.videoSessionsArray[i] as! TalkfunRtcModel
      
            model.drawPower = false
           }
        UIView.performWithoutAnimation {
            self.reloadData()
        }
   
    }
    //所有学生下讲台
   @objc func allTheStudentsWalkedOffThePodium()
    {
        let copy = NSMutableArray.init(array: self.videoSessionsArray)
        for i in 0..<copy.count {
            let model = copy[i] as! TalkfunRtcModel
            
            //等于学生
            if (model.role == .roleeUser) {
                self.videoSessionsArray.remove(model)
                
            }
        }
        
        UIView.performWithoutAnimation {
            self.reloadData()
        }
    }
    @objc func updateModel(_ model:TalkfunRtcModel)
    {
        if (model != nil) {
         if(self.isFull){
             if (self.vc != nil) {
                 self.dealSingleTap(self.vc!)
             }
           }
           
            var  Index:Bool = false
           
           //初始化数据
            for i in 0..<self.videoSessionsArray.count {
         
               let obj = self.videoSessionsArray[i] as!TalkfunRtcModel

               if (obj.xid == model.xid) {
                   Index = true
                   obj.score = model.score
                   obj.audio = model.audio
                   obj.drawPower = model.drawPower
                   obj.video = model.video
                   
               }
           }

           if (Index == false) {
               if ( model.role == .roleSpadmin) {
                   self.videoSessionsArray.insert(model, at: 0)
                 
               }else{
                   self.videoSessionsArray.add(model)
               }
              
           }
           //局部刷新
            self.reloadData()
          
        }
    }
    func getCount()->NSInteger
    {
        
        if (self.videoSessionsArray.count == 3) {

            return self.videoSessionsArray.count+1
           
        } else if (self.videoSessionsArray.count == 5) {
         
            return self.videoSessionsArray.count+1
        } else if (self.videoSessionsArray.count==7||self.videoSessionsArray.count==8){
            return 9
        }  else if (self.videoSessionsArray.count==10||self.videoSessionsArray.count==11){
            return 12
        } else if (self.videoSessionsArray.count==13||self.videoSessionsArray.count==14){
            return 15
        } else if (self.videoSessionsArray.count == 16) {
            return 18
        } else {
        
            return self.videoSessionsArray.count
            
        }
    }
    func getSize()->CGSize
    {
        
        let cellHeight:CGFloat = self.collectionView!.frame.size.height
        let cellWidth:CGFloat = self.collectionView!.frame.size.width
      
        var x:CGFloat = 0
        var y:CGFloat = 0
        self.layout.sectionInset = UIEdgeInsets(top: 0, left: 60, bottom: 0, right: 60);
        if (self.videoSessionsArray.count == 1) {
            y = 5;
            let height = cellHeight-10
            let width = height/3.0*4
            x = (cellWidth-width)/2.0
            self.layout.sectionInset = UIEdgeInsets(top: y, left: x, bottom: y, right: x)
            
            return CGSize(width: width, height: height)
        } else if (self.videoSessionsArray.count == 2) {
            x = 67;
            let width = (cellWidth-67*2-5 )/2.0;
            let height = width * 0.75
            y = (cellHeight - height)/2.0
            self.layout.sectionInset = UIEdgeInsets(top: y, left: x, bottom: y, right: x)
            return CGSize(width: width, height: height)
        } else if (self.videoSessionsArray.count == 3 || self.videoSessionsArray.count == 4) { //3
            y = 5;
            let height = (cellHeight-15)/2.0;
            let width = height/3.0*4;
            x = (cellWidth - width * 2 - 5)/2.0;
            self.layout.sectionInset = UIEdgeInsets(top: y, left: x, bottom: y, right: x)
            return CGSize(width: width, height: height)
        } else if (self.videoSessionsArray.count == 5 || self.videoSessionsArray.count == 6) {//5
            x = 91.5;
            let width = (cellWidth-(x*2)-(5*2))/3.0
            let height = width * 0.75
            y = (cellHeight-height*2-5)/2.0
            self.layout.sectionInset = UIEdgeInsets(top: y, left: x, bottom: y, right: x)
            return CGSize(width: width, height: height)
        }  else {
            y = 5;
            let height = (cellHeight-20 )/3.0
            let width = height/3.0*4
            x = (cellWidth-width*3-10)/2
            self.layout.sectionInset = UIEdgeInsets(top: y, left: x, bottom: y, right: x);
            return CGSize(width: width, height: height)
        }
    }
    func objectDidDragged(_ vc: TF1to16VideoAreaCell) {
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TFGalleryViewDelegate.GalleryobjectDidDragged(_:))))!{
            self.delegate?.GalleryobjectDidDragged(vc)
           
        }
    }
    
    func dealSingleTap(_ vc: TF1to16VideoAreaCell) {
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TFGalleryViewDelegate.GallerydealSingleTap(_:))))!{
            self.delegate?.GallerydealSingleTap(vc)
           
        }
    }
}
@objc protocol TFGalleryViewDelegate : NSObjectProtocol {
    //双击了
    func GalleryobjectDidDragged(_ vc : TF1to16VideoAreaCell)
    //单击
    func GallerydealSingleTap(_ vc : TF1to16VideoAreaCell)
}
